package com.chb.filters;

import com.chb.config.MyUserDetailsConfig;
import io.jsonwebtoken.Claims;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author CHB
 * @createTime 2022-6-16 10:34
 */
public class JwtFilter extends OncePerRequestFilter {

    @Resource
    private JwtUtils jwtUtils;

    @Resource
    private MyUserDetailsConfig userDetailsConfig;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader("token");
        if(StringUtils.isEmpty(token)){
            filterChain.doFilter(request,response);
            return;
        }
        // 解析token
        Claims claims = jwtUtils.parseToken(token);
        if(claims == null){
            System.out.println("token error");
            filterChain.doFilter(request,response);
            return;
        }
        String name = (String) claims.get("name");
        UserDetails userDetails = userDetailsConfig.loadUserByUsername(name);
        // 解析成功放入security上下文
        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails,null,userDetails.getAuthorities());
        authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
        SecurityContextHolder.getContext().setAuthentication(authentication);
        filterChain.doFilter(request,response);
    }
}
